package cn.bs.controller;


import cn.bs.domain.dao.Canteen;
import cn.bs.domain.dao.Dishes;
import cn.bs.domain.dao.Orders;
import cn.bs.domain.dao.Seat;
import cn.bs.domain.pojo.DishesPOJO;
import cn.bs.domain.pojo.Result;
import cn.bs.domain.vo.CanteenVO;
import cn.bs.domain.vo.DishesVO;
import cn.bs.domain.vo.PayOrderVO;
import cn.bs.mapper.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/canteen")
public class CanteenController {

    @Autowired
    private CanteenMapper canteenMapper;

    @Autowired
    private DishesMapper dishesMapper;

    @Autowired
    private SeatMapper seatMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/getCanteen")
    public Result getCanteen(@RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "10") int size) {
        int offset = (page - 1) * size;
        List<Canteen> canteens = canteenMapper.getCanteenListWithPagination(offset, size);
        CanteenVO canteenVO = new CanteenVO();
        canteenVO.setCanteens(canteens);
        canteenVO.setTotal(canteenMapper.getTotalCanteens());
        return Result.ok(canteenVO);
    }


    @GetMapping("/getCanteenById")
    public Result getCanteenById(Integer canteenId) {
        Canteen canteen =canteenMapper.getById(canteenId);
        return Result.ok(canteen);
    }

    @GetMapping("/getDishesByCanteenId")
    public Result getDishesByCanteenId(Integer canteenId) {
        System.out.println("获取餐厅菜品");
        System.out.println(canteenId);

        List<Dishes> dishes =dishesMapper.getDishesByCanteenId(canteenId);
        List<DishesPOJO> dishesPOJOs = dishes.stream().map(dish -> {
            DishesPOJO dishesPOJO = new DishesPOJO();
            dishesPOJO.setId(dish.getId());
            dishesPOJO.setCanteenId(dish.getCanteenId());
            String canteenName = canteenMapper.getById(dish.getCanteenId()).getName();
            dishesPOJO.setCanteenName(canteenName);
            String typeName = typeMapper.getTypeName(dish.getTypeId());
            dishesPOJO.setTypeId(dish.getTypeId());
            dishesPOJO.setTypeName(typeName);
            dishesPOJO.setPrice(dish.getPrice());
            dishesPOJO.setDescription(dish.getDescription());
            dishesPOJO.setName(dish.getName());
            dishesPOJO.setImage(dish.getImage());
            return dishesPOJO;
        }).toList();

        DishesVO dishesVO = new DishesVO();
        dishesVO.setDishes(dishesPOJOs);
        dishesVO.setTotal(dishes.size());

        return Result.ok(dishesVO);
    }

    @GetMapping("/getSeatList")
    public Result getSeatList(Integer canteenId) {
        System.out.println("获取餐厅座位");
        System.out.println(canteenId);
        List<Seat> seats =seatMapper.getSeatList(canteenId);
        return Result.ok(seats);
    }

    @PostMapping("/checkSeat")
    public Result checkSeat(HttpServletRequest request,@RequestParam Integer seatId,
                            @RequestParam Integer status) {
        System.out.println("选择座位");
        System.out.println(seatId);
        //在sessionStorage中拿token，从redis中拿userId
        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(request.getHeader("Authorization")));
        Seat seat =seatMapper.getById(seatId);
        if (seat.getStatus() == 1) {
            return Result.fail("该座位已被预定，请选择其它位置");
        }

        Orders order = new Orders();

        if (status == 0) {
            order = new Orders(null,
                    userId, seat.getCanteenId(), seatId, seat.getPrice(), new Date(),
                    0.0, null, 0);
        }else if (status == 1) {
            order = new Orders(null,
                    userId, seat.getCanteenId(), seatId, seat.getPrice(), new Date(),
                    seat.getPrice(), new Date(), 1);
            seat.setStatus(1);
            seatMapper.updateById(seat);
        }

        //创建一条座位预定的订单
        orderMapper.insertOrder(order);
        PayOrderVO payOrderVO = new PayOrderVO();
        payOrderVO.setId(order.getId());
        payOrderVO.setUserName(userMapper.getById(order.getUserId()).getName());
        payOrderVO.setCanteenName(canteenMapper.getById(order.getCanteenId()).getName());
        payOrderVO.setSeatId(order.getSeatId());
        payOrderVO.setOrderAmount(order.getOrderAmount());
        payOrderVO.setOrderDate(order.getOrderDate());
        payOrderVO.setPayAmount(order.getPayAmount());
        payOrderVO.setPayDate(order.getPayDate());
        payOrderVO.setStatus(order.getStatus());

        return Result.ok(payOrderVO);
    }


    @PostMapping("/pay")
    public Result pay(HttpServletRequest request,@RequestParam Integer orderId) {

        Integer userId = Integer.valueOf(stringRedisTemplate
                .opsForValue().get(request.getHeader("Authorization")));
        if (userId == null){
            return Result.fail("用户未登录");
        }

        System.out.println("userId :" + userId);
        Orders order = orderMapper.getById(orderId);

        System.out.println("orderUserId :" + order.getUserId());
        if (order == null){
            return Result.fail("订单不存在");
        }

        if (!Objects.equals(order.getUserId(), userId)){
            return Result.fail("该订单不属于您，无需支付");
        }

        if (order.getStatus() == 1){
            return Result.fail("该订单已支付");
        }else if (order.getStatus() == 2){
            return Result.fail("该订单已取消");
        }
        Seat seat = seatMapper.getById(order.getSeatId());
        if (seat.getStatus() == 1){
            return Result.fail("该座位已被预定，请选择其它位置");
        }

        order.setPayAmount(order.getOrderAmount());
        order.setPayDate(new Date());
        order.setStatus(1);

        seat.setStatus(1);
//        seatMapper.updateById(seat);
//
//        orderMapper.updateById(order);

        return Result.ok("");

    }


}
